/*
 * 文件名： SpdbExPayServiceImpl.java
 * 
 * 工程名称: bis-service
 *
 * Gopay
 *
 * 创建日期： 2016年4月11日
 *
 * Copyright(C) 2016, by www.gopay.com.cn Inc.All rights reserved.
 *
 * 原始作者: 宣广海
 *
 */
package com.gopay.bis.service.bank.impl.expay;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.bis.manager.bank.BankOrderManager;
import com.gopay.bis.manager.bank.expay.SpdbExPayManager;
import com.gopay.bis.service.bank.validcode.ValidCodeSupportController;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.QueryNeedCertConstants;
import com.gopay.common.constants.bank.SmsConstants;
import com.gopay.common.constants.bank.SpdbConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.ExPayBaseMessage;
import com.gopay.common.domain.bank.spdb.expay.SpdbMessageExPay;
import com.gopay.common.exception.GopayException;
import com.gopay.common.util.TransUtil;
import com.gopay.remote.bank.ExPayInteractRemoteService;

/**
 * 浦发银行快捷支付业务实现类
 * 
 * @author wjq
 * @date 2016年4月11日
 */
@Service("spdbExpayServiceImpl")
public class SpdbExPayServiceImpl implements ExPayInteractRemoteService {

    @Resource(name = "spdbExPayManager")
    private SpdbExPayManager spdbExPayManager;
    @Resource(name = "bankOrderManager")
    private BankOrderManager bankOrderManager;

    // 验证码处理类
    public ValidCodeSupportController validCodeController;

    /**
     * 快捷签约接口 因浦发快捷支付签约分三步，这是第一步
     * 
     * @param baseMsg
     * @return
     * @throws Exception
     */
    public Result certification(ExPayBaseMessage baseMsg) {
        Result result = new Result(false);
        try {
            SpdbMessageExPay message = new SpdbMessageExPay();
            BeanUtils.copyProperties(baseMsg, message);
            SpdbMessageExPay signMsg = (SpdbMessageExPay) spdbExPayManager.certification(message);
            if ((SpdbConstants.RESPCODE_SUCCESS).equals(signMsg.getRespCode())) {
                result.setModel("flag", true);
            } else {
                result.setModel("flag", false);
                result.setModel("retMsg", signMsg.getErrorMsg());
            }
            result.setDefaultModel(signMsg);
            result.setSuccess(true);
        } catch (GopayException e) {
            BankLogUtils.printServiceImplExceptionLog(e);
            result.setResultCode(e.getErrCode());
        } catch (Exception ex) {
            BankLogUtils.printServiceImplExceptionLog(ex);
            result.setResultCode(ProcCodeConstants.PROC_CODE_100E6076);
        }
        return result;
    }

    /**
     * 快捷支付付款接口
     * 
     * @param baseMsg
     * @return ExPayBaseMessage
     * @throws Exception
     *             超时等信息需捕获处理
     */
    public Result payment(ExPayBaseMessage baseMsg) {
        Result result = new Result(false);
        try {
            baseMsg.setBankOrderId(TransUtil.processOrderIdTo12Digit(baseMsg.getOrderId()));
            SpdbMessageExPay message = new SpdbMessageExPay();
            BeanUtils.copyProperties(baseMsg, message);
            message = (SpdbMessageExPay) spdbExPayManager.payment(message);
            result.setModel("res", message);
            result.setDefaultModel(message == null ? false : true);
            result.setSuccess(true);
            Map<String, String> param = new HashMap<String, String>();
            if ((SpdbConstants.RESPCODE_SUCCESS).equals(message.getRespCode())) {
                param.put("orderId", baseMsg.getOrderId());
                param.put("amt", message.getTranAmt());
                param.put("cardType", "Unknown");
                param.put("notifyNum", "1");
                param.put("payStatus", "00");
                param.put("retCode", "00");
                param.put("retMsg", "验签成功");
                param.put("signData", "");
                param.put("isFront", String.valueOf(baseMsg.isFront()));
                result.setModel("isNotifyCashier", param);
                result.setModel("flag", true);
                result.setDefaultModel(true);
                result.setOrderStatus(true);
            } else {
                // 通知后台地址该订单失败
                param.put("orderId", baseMsg.getOrderId());
                param.put("amt", message.getTranAmt());
                param.put("cardType", "Unknown");
                param.put("notifyNum", "1");
                param.put("payStatus", "01");
                param.put("retCode", "01");
                // 记录数据库失败信息 add by zhengxue 20170313
                param.put("retMsg", StringUtils.isEmpty(message.getErrorMsg()) ? "交易失败" : message.getErrorMsg());
                param.put("signData", "");
                param.put("isFront", String.valueOf(baseMsg.isFront()));
                result.setModel("isNotifyCashier", param);
                result.setModel("flag", false);
                result.setOrderStatus(false);
                result.setBankRetCode(message.getBankRetCode());//add by liuyu, 20170802, 快捷API失败通知
            }
        } catch (GopayException e) {
            BankLogUtils.printServiceImplExceptionLog(e);
            result.setResultCode(e.getErrCode());
        } catch (Exception ex) {
            BankLogUtils.printServiceImplExceptionLog(ex);
            result.setResultCode(ProcCodeConstants.PROC_CODE_100E6057);
        }
        return result;
    }

    /**
     * 快捷订单单笔查询接口
     * 
     * @param baseMsg
     * @return
     * @throws Exception
     */
    public Result queryOrder(ExPayBaseMessage baseMsg) {
        Result result = new Result(false);
        try {
            SpdbMessageExPay message = new SpdbMessageExPay();
            BeanUtils.copyProperties(baseMsg, message);
            message = (SpdbMessageExPay) spdbExPayManager.query(message);
            result.setDefaultModel(message);
            result.setSuccess(true);
            result.setBankRetCode(message.getBankRetCode());//add by liuyu, 20170803, 快捷API失败通知
        } catch (GopayException e) {
            BankLogUtils.printServiceImplExceptionLog(e);
            result.setResultCode(e.getErrCode());
        } catch (Exception ex) {
            BankLogUtils.printServiceImplExceptionLog(ex);
            result.setResultCode(ProcCodeConstants.PROC_CODE_100E6058);
        }
        return result;
    }

    /**
     * 发送短信验证码接口 因浦发快捷支付签约分三步，这是第二步
     */
    public Result sendSms(ExPayBaseMessage baseMsg) {
        Result result = new Result(false);
        SpdbMessageExPay message = new SpdbMessageExPay();
        BeanUtils.copyProperties(baseMsg, message);
        try {
        	/*
            Map<String, String> smsRes = validCodeController.createValidCode(message);
            String validCode = smsRes.get("validCode");
            if (StringUtils.isNotBlank(validCode)) {
                message.setValidateCode(validCode);
                message = (SpdbMessageExPay) spdbExPayManager.sendSpdbSMS(message);
                if ((SpdbConstants.RESPCODE_SUCCESS).equals(message.getRespCode())
                        || (SpdbConstants.SIGN_SUCCESS).equals(message.getErrorCode())) {
                    // 短信发送成功
                    smsRes = validCodeController.buildSendLog(baseMsg, Integer.valueOf(smsRes.get("sendCount")));
                    result.setModel("flag", true);
                } else {
                    // 短信发送失败
                    result.setModel("flag", false);
                    smsRes.put("resCode", ProcCodeConstants.PROC_CODE_100E6096);
                    smsRes.put("retMsg", "获取短信验证码失败，请稍后再试");
                }
            } else {
                // 短信发送失败
                result.setModel("flag", false);
            }
            result.setModel("sendCount", smsRes.get("sendCount"));
            result.setModel("retMsg", smsRes.get("retMsg"));
            result.setModel("resCode", smsRes.get("resCode"));
            result.setResultCode(smsRes.get("resCode"));
            result.setSuccess(true);
            */
        	result.setModel("flag", true);
        	result.setModel("sendCount", "1");
            result.setModel("retMsg", "短信发送成功");
            result.setModel("resCode", ProcCodeConstants.PROC_CODE_100E6102);
            result.setResultCode(ProcCodeConstants.PROC_CODE_100E6102);
            result.setSuccess(true);
        } catch (Exception ex) {
            BankLogUtils.printServiceImplExceptionLog(ex);
            result.setResultCode(ProcCodeConstants.PROC_CODE_100E6077);
        }
        return result;
    }

    /**
     * 校验短信
     */
    public Result checkSms(ExPayBaseMessage baseMsg) {
        Result result = new Result(false);
        SpdbMessageExPay message = new SpdbMessageExPay();
        BeanUtils.copyProperties(baseMsg, message);
        try {
        	/*
            Map<String, String> smsRes = validCodeController.checkSMS(baseMsg);
            if (ProcCodeConstants.PROC_CODE_100E6091.equals(smsRes.get("resCode"))) {
                // 浦发直连快捷支付---校验成功后，发给银行2状态，此时银行可能会因该卡号重复签约，报错，但并不影响后续的支付操作,浦发返回成功后，该卡签约成功，插入表。
                SpdbMessageExPay ress = (SpdbMessageExPay) spdbExPayManager.sendSpdbResult(message);
                if ((SpdbConstants.RESPCODE_SUCCESS).equals(ress.getRespCode())
                        || (SpdbConstants.SIGN_SUCCESS).equals(ress.getRespCode())
                        || (SpdbConstants.SIGN_SUCCESS.equals(ress.getErrorCode()))) {
                    result.setModel("flag", true);
                } else {
                    result.setModel("flag", false);
                    smsRes = validCodeController.buildCheckLog(baseMsg, Integer.valueOf(smsRes.get("failCount")));
                }
            } else {
                result.setModel("flag", false);
            }
            if (!(boolean) result.getModel("flag")
                    && !ProcCodeConstants.PROC_CODE_100E6099.equals(smsRes.get("resCode"))) {
                Map<String, String> freezeRes = validCodeController.freezeCard(message);
                if (freezeRes != null)
                    smsRes = freezeRes;
            }
            result.setModel("failCount", smsRes.get("failCount"));
            result.setModel("retMsg", smsRes.get("retMsg"));
            result.setModel("resCode", smsRes.get("resCode"));
            result.setResultCode(smsRes.get("resCode"));
            result.setSuccess(true);
            */
            
        	SpdbMessageExPay ress = (SpdbMessageExPay) spdbExPayManager.sendSpdbResult(message);
            if ((SpdbConstants.RESPCODE_SUCCESS).equals(ress.getRespCode())
                    || (SpdbConstants.SIGN_SUCCESS).equals(ress.getRespCode())
                    || (SpdbConstants.SIGN_SUCCESS.equals(ress.getErrorCode()))) {
                result.setModel("flag", true);
                result.setModel("retMsg", "短信验证码输入正确");
                result.setModel("resCode", ProcCodeConstants.PROC_CODE_100E6091);
                result.setResultCode(ProcCodeConstants.PROC_CODE_100E6091);
            } else {
                result.setModel("flag", false);
                result.setModel("retMsg", "短信验证码输入错误");
                result.setModel("resCode", ProcCodeConstants.PROC_CODE_100E6098);
                result.setResultCode(ProcCodeConstants.PROC_CODE_100E6098);
            }
            result.setModel("failCount", "0");
            result.setSuccess(true);
            
        	
        } catch (Exception e) {
            BankLogUtils.printServiceImplExceptionLog(e);
            result.setResultCode(ProcCodeConstants.PROC_CODE_100E6078);
        }
        return result;
    }
    

    /**
     * 返回结果处理接口
     */
    public Result verify(ExPayBaseMessage baseMsg) {
        return null;
    }

    @Override
    public Result refund(ExPayBaseMessage baseMsg) {
        return null;
    }

    @Override
    public Result cancel(ExPayBaseMessage baseMsg) {
        return null;
    }

    @Override
    public Result sign(ExPayBaseMessage baseMsg) {
        return null;
    }

    /**
     * 是否需要cvv2
     */
    public Result queryCvn(ExPayBaseMessage baseMsg) {
        Result result = new Result();
        result.setSuccess(true);
        result.setModel("flag", true);
        result.setModel("isQueryCVN", SpdbConstants.SPDB_EXPAY_ISQUERYCVN);
        return result;
    }

    @Override
    public Result treatyQuery(ExPayBaseMessage baseMsg) {
        return null;
    }

    public ValidCodeSupportController getValidCodeController() {
        return validCodeController;
    }

    public void setValidCodeController(ValidCodeSupportController validCodeController) {
        this.validCodeController = validCodeController;
    }

    @Override
    public Result queryNeedCert(ExPayBaseMessage baseMsg) {
        // TODO Auto-generated method stub
        return null;
    }
/*	@Override
	public Result refundQuery(ExPayBaseMessage baseMsg) {
		// TODO Auto-generated method stub
		return null;
	}*/

    @Override
    public Result refundBack(ExPayBaseMessage baseMsg) {
        // TODO Auto-generated method stub
        return null;
    }
}
